<template>
  <n-grid x-gap="12" :cols="4">
    <n-gi :span="1">
      <n-card :bordered="false" title="个人信息" class="card-header-border">
        <n-grid x-gap="12" :cols="1">
          <n-gi>
            <div style="display:flex;justify-content: center; align-items:center;width: 100%;padding-bottom: 20px">
              <div>
                <div class="avatar-img">
                  <img v-if="admin_setting.avatar" :src="'/api/admin/file/'+admin_setting.avatar"
                       style="width: 120px; height: 120px"
                       alt=""/>
                </div>
                <div style="text-align: center;margin-top: 5px;">
                  <n-upload
                      :show-file-list="false"
                      directory-dnd
                      action="/api/sys/upload_avatar"
                      accept=".jpg,.jpeg,.png,.gif"
                      :headers="uploadHeader"
                      @finish="uploadAvatarFinish($event)">
                    <n-button>{{admin_setting.avatar?'确认更换':'上传头像'}}</n-button>
                  </n-upload>
                </div>
              </div>
            </div>
          </n-gi>
        </n-grid>
        <n-list bordered class="user_info">
          <n-list-item style="padding: 7px 5px;">
            <span class="prefix">
              <n-icon :size="14">
                <UserFilled/>
              </n-icon>
              管理员名称
            </span>
            <span class="suffix">{{ admin_setting.account }}</span>
          </n-list-item>
          <n-list-item style="padding: 7px 5px;">
            <span class="prefix">
              <n-icon>
                <UserTag/>
              </n-icon>
              管理员昵称</span>
            <span class="suffix">{{ admin_setting.nickName }}</span>
          </n-list-item>
          <n-list-item style="padding: 7px 5px;">
            <span class="prefix">
              <n-icon>
                <Phone16Filled/>
              </n-icon>
              手机号码
            </span>
            <span class="suffix">{{ admin_setting.phone }}</span>
          </n-list-item>
          <n-list-item style="padding: 7px 5px;">
            <span class="prefix">
              <n-icon>
                <EmailFilled/>
              </n-icon>
              电子邮箱
            </span>
            <span class="suffix">{{ admin_setting.email }}</span>
          </n-list-item>
          <n-list-item style="padding: 7px 5px;">
            <span class="prefix">
              <n-icon>
                <Users/>
              </n-icon>
              所属角色</span>
            <span class="suffix">{{ admin_setting.roles }}</span>
          </n-list-item>
          <n-list-item style="padding: 7px 5px;">
            <span class="prefix">
              <n-icon>
                <DateRangeRound/>
              </n-icon>
              创建时间
            </span>
            <span class="suffix">{{ admin_setting.create_time }}</span>
          </n-list-item>
        </n-list>
      </n-card>
    </n-gi>
    <n-gi :span="3">
      <n-card :bordered="false" title="基本资料" class="card-header-border">
        <n-space>
          <n-form ref="admin_setting_form"
                  label-placement="left"
                  label-width="80"
                  :model="admin_form" :rules="admin_setting_rules" style="width: 400px">
            <n-form-item path="nick_name" label="昵称">
              <n-input v-model:value="admin_form.nickName" clearable/>
            </n-form-item>
            <n-form-item path="mail" label="邮箱">
              <n-auto-complete v-model:value="admin_form.email" :options="emailOptions" placeholder="邮箱" clearable/>
            </n-form-item>
            <n-form-item path="phone" label="电话">
              <n-input v-model:value="admin_form.phone" maxlength="11" clearable/>
            </n-form-item>
            <n-form-item label=" ">
              <n-button type="primary" @click="updateAdmin" :loading="handleSubmitLoading">更新信息</n-button>
            </n-form-item>
          </n-form>
        </n-space>
      </n-card>
    </n-gi>
  </n-grid>


</template>

<script lang="ts" setup>
import {onBeforeMount, computed, ref} from "vue";
import {FormItemRule, useMessage} from "naive-ui";
import {getAdminInfo, updateAdminInfo} from "@/api/user.ts";
import {emails_suffix} from "@/config";
import {UseUserStore} from "@/stores/user.ts"
import {UserFilled} from "@vicons/carbon"
import {Phone16Filled} from "@vicons/fluent"
import {DateRangeRound, EmailFilled} from "@vicons/material"
import {UserTag, Users} from "@vicons/fa"
import { uploadFileHeader} from "@/util/Auth.ts";

const userStore = UseUserStore();
const message = useMessage();
const handleSubmitLoading = ref(false);
//表单ref
const admin_setting_form = ref();
const admin_setting = ref({
  account: "",
  nickName: "",
  email: "",
  phone: "",
  roles: "",
  avatar: null,
  create_time: null,
  web_site:null,
});
const admin_form=ref({
  nickName: "",
  email: "",
  phone: "",
  avatar:null,
})

//上传文件头部
const uploadHeader = computed(() => {
  return uploadFileHeader();
});
const admin_setting_rules = computed(() => {
  return {
    nick_name: {
      required: true,
      trigger: ["blur", "change"],
      message: "请输入昵称",
    },
    phone: {
      trigger: ["blur", "input"],
      validator: (_rule: FormItemRule, value: string) => {
        let reg = /^1[3|4|5|6|7|8|9][0-9]{9}/;
        return new Promise<void>((resolve, reject) => {
          if (value && !reg.test(value)) {
            reject(Error("请输入正确格式的手机号码"));
          } else {
            resolve();
          }
        });
      },
    },
  };
});
//邮箱自动填充
const emailOptions = computed(() => {
  return emails_suffix.map((suffix) => {
    if (admin_form.value.email){
      const prefix = admin_form.value.email.split("@")[0];
      return {
        label: prefix + suffix,
        value: prefix + suffix,
      };
    }
  });
});


const get_info = () => {
  getAdminInfo().then((res: any) => {
    const {code,data}=res;
    if (code === 200) {
      admin_setting.value.account = data.account;
      admin_setting.value.nickName = data.nickName;
      admin_setting.value.email = data.email;
      admin_setting.value.phone = data.phone;
      admin_setting.value.roles = data.role;
      admin_setting.value.avatar =data.avatar?data.avatar:null;
      admin_setting.value.web_site =data.web_site;
      admin_setting.value.create_time =data.createTime;
      admin_form.value.nickName = data.nickName;
      admin_form.value.email = data.email;
      admin_form.value.phone = data.phone;
    }
  })
}

const updateAdmin = () => {
  const data = {
    name: admin_form.value.nickName,
    e_mail: admin_form.value.email,
    phone: admin_form.value.phone,
    avatar: admin_form.value.avatar,
  };
  handleSubmitLoading.value = true;
  updateAdminInfo(data).then((res: any) => {
    message.create(res.message, {
      type: res.code === 200 ? "success" : "error",
      duration: 1500,
      onLeave() {
        admin_setting.value.nickName = admin_form.value.nickName;
        admin_setting.value.email = admin_form.value.email;
        admin_setting.value.phone = admin_form.value.phone;
        if (admin_form.value.avatar){
          const avatar=admin_setting.value.web_site+admin_form.value.avatar;
          userStore.setAvatar(avatar);
        }
        handleSubmitLoading.value = false;
      },
    });
  })
}
//上传头像返回数据
const uploadAvatarFinish = ({event}: { event?: ProgressEvent | any }) => {
  const res=JSON.parse(event['currentTarget']['response']);
  const {code}=res;
  if (code===200){
    admin_setting.value.avatar = res.data.avatar;
    userStore.setAvatar(res.data.avatar);
    message.success("上传成功")
  }
};


onBeforeMount(() => {
  get_info();
})
</script>

<style scoped lang="scss">
.avatar-img {
  width: 120px;
  height: 120px;
  border-radius: 3px;
  border: 1px dashed rgb(243, 243, 245);
  transition: all .3s cubic-bezier(0.4, 0, 0.2, 1);

  img {
    border-radius: 3px;
  }
}

.dark .avatar-img {
  border: 1px dashed rgba(255, 255, 255, 0.09);
  transition: all .3s cubic-bezier(0.4, 0, 0.2, 1);
}

:deep(.avatar-img-upload .n-form-item-blank) {
  display: block;
}

:deep(.user_info) {
  border-left: none;
  border-radius: 0;
  border-right: none;

  .n-list-item > .n-list-item__main {
    display: flex;
    justify-content: space-between;

    i {
      position: relative;
      top: 2px;
    }
  }
}

</style>